package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.UserDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName CheckItemServiceImpl
 * @Description TODO
 * @Author ly
 * @Company 深圳黑马程序员
 * @Date 2019/9/11 9:55
 * @Version V1.0
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public User findUserByUsername(String username) {
        return userDao.findUserByUsername(username);
    }

    @Override
    public PageResult pageQuery(Integer currentPage, String queryString, Integer pageSize) {

        //使用分页插件PageHelper, 设置当前页, 每页最多显示的记录数
        PageHelper.startPage(currentPage, pageSize);

        //响应分页插件的page对象
        Page<User> page = userDao.selectByCondition(queryString);

        return new PageResult(page.getTotal(), page.getResult());

    }

    @Override
    public void add(User user, List<Integer> roleIds) {
        userDao.add(user);

        setUserAndRole(user.getId(), roleIds);

    }

    @Override
    public void update(User user) {
        userDao.update(user);
    }

    @Override
    public User findById(Integer id) {
        User user = userDao.findById(id);

        return user;
    }

    @Override
    public List<Role> selectRoleIdsOfAUser(Integer id) {

        List<Role> list = userDao.selectRoleIdsOfAUser(id);

        return list;

    }

    @Override
    public void remove(Integer id) {

        //查询当前检查项是否和检查组关联
        int count = userDao.findCountByUserId(id);
        if (count > 0) {
            userDao.deleteMidTableByUserId(id);
        }
        userDao.deleteById(id);

    }

    private void setUserAndRole(Integer userId, List<Integer> roleIds) {

        if(roleIds != null) {
            for (Integer roleId : roleIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("user_id", userId);
                map.put("roleId_id", roleId);

                userDao.setUserAndRole(map);
            }
        }

    }
}
